"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : Binary
Case Name   : COPY TO把一个有binary类型的表数据拷贝到一个文件
Create At   : 2022/03/24
Owner       : @li-xin12345
Description :
    1. 创建兼容B库，检查dolphin插件
    2. 创建表并插入binary类型数据
    3. 创建文件,表数据copy to到一个文件
    4. 清理环境
Expect      :
    1. 创建成功，插件自动加载
    2. 创建并插入成功
    3. 创建文件成功，copy成功
    4. 成功
History     :
"""

import os
import unittest

from yat.test import Node
from yat.test import macro
from testcase.utils.Common import Common
from testcase.utils.Logger import Logger
from testcase.utils.Constant import Constant
from testcase.utils.CommonSH import CommonSH


class CopySupportBinary(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.user = Node('PrimaryDbUser')
        self.common = Common()
        self.constant = Constant()
        self.commonsh = CommonSH('PrimaryDbUser')
        self.file = os.path.join(macro.DB_INSTANCE_PATH, 'f_binary_040.txt')
        status = self.commonsh.get_db_cluster_status("detail")
        self.log.info(status)
        self.assertTrue("Normal" in status or "Degraded" in status)
        self.db_name = 'db_binary_040'
        self.tb_name = 't_binary_040'

    def test_binary(self):
        text = '-----step1:创建兼容B库，检查dolphin插件;expect:创建成功-----'
        self.log.info(text)
        sql_cmd = f"drop database if exists {self.db_name};" \
                  f"create database {self.db_name} " \
                  f"dbcompatibility ='B';"
        self.log.info(sql_cmd)
        sql_res = self.commonsh.execut_db_sql(sql_cmd, dbname='postgres')
        self.log.info(sql_res)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, sql_res,
                      "执行失败" + text)

        sql_cmd = "select extname from pg_extension where extname ='dolphin';"
        self.log.info(sql_cmd)
        sql_res = self.commonsh.execut_db_sql(sql_cmd,
                                              dbname=self.db_name)
        self.log.info(sql_res)
        self.assertIn('dolphin', sql_res, '查询失败')

        text = '-----step2:创建表并插入binary类型数据;expect:成功-----'
        self.log.info(text)
        res = self.commonsh.execut_db_sql(f'''
        drop table if exists {self.tb_name};
        create table {self.tb_name}(field_name binary(6), id int);
        insert into {self.tb_name} values ('10101', 1);
        insert into {self.tb_name} values ('1001', 6);
        insert into {self.tb_name} values ('01101', 6);
        insert into {self.tb_name} values ('1100', 6);''', dbname=self.db_name)
        self.log.info(res)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS,
                      res, "执行失败：" + text)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS,
                      res, "执行失败：" + text)
        self.assertEqual(res.count(self.constant.INSERT_SUCCESS_MSG),
                         4, "执行失败：" + text)

        text = '-----step3:创建文件,表数据copy to到文件;' \
               'expect:创建成功，copy成功-----'
        self.log.info(text)
        self.user.sh(f'rm -rf {self.file}; touch {self.file}')
        res = self.commonsh.execut_db_sql(f"copy {self.tb_name} to"
                                          f" '{self.file}';",
                                          dbname=self.db_name)
        self.log.info(res)
        self.assertEqual('COPY 4', res, "执行失败" + text)
        file_res = self.user.sh(f"cat {self.file}").result()
        self.log.info(file_res)
        self.assertTrue(file_res.count('6') == 3)

    def tearDown(self):
        text = '-----step4:清理环境;expect:成功-----'
        self.log.info(text)
        drop_res = self.commonsh.execut_db_sql(
            f"drop database if exists {self.db_name};", dbname='postgres')
        self.log.info(drop_res)
        check_cmd = f'rm -rf {self.file};' \
                    f'if [ -d {self.file} ]; ' \
                    f'then echo "exists"; else echo "not exists"; fi'
        self.log.info(check_cmd)
        rm_res = self.common.get_sh_result(self.user, check_cmd)
        self.log.info(rm_res)
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, drop_res,
                      "执行失败：" + text)
        self.assertEqual('not exists', rm_res, '文件删除失败')
        self.log.info(f"-----{os.path.basename(__file__)} end-----")